# -*- coding: utf-8 -*-
#   生成领料单导入
# @Time    ： 2025/11/12  14:58
# @Auther  ： 徐良
# File     :  erp_interface.py

from typing import Optional, Union, Dict, Any
from PySide6.QtCore import Signal, Qt, Slot, QItemSelection, QModelIndex
from PySide6.QtGui import QPixmap, QPainter, QColor
from erpInterface.ui.erpInterfaceUI import Ui_Form
from PySide6.QtWidgets import QApplication, QLabel, QTableWidgetItem, QWidget, QHBoxLayout, QPushButton, QHeaderView
from baseClass.winPanel.baseQWidget import BaseQWidget
from baseClass.model.formModel import FormModel
from utils.alone.aloneWorkAssistant import AloneWorkAssistant
from baseClass.winPanel.interface_style import apply_styles
from mesParts.button.buttons import TextButton
from baseClass.tools.dialogUtils import DialogUtils
from functools import partial
# 在文件开头添加导入（关键）
import win32com.client
import pythoncom



class ErpInterface(BaseQWidget, AloneWorkAssistant, Ui_Form):

    def __init__(self, p_dict:Dict[str, Any]=None,parent=None):
        super().__init__(parent)
        self.DEFAULT_MS_DICT = p_dict
        self.ms_number = self.DEFAULT_MS_DICT.get('ms_number')
        # # 创建工作类并初始化
        self.create_factory(self.DEFAULT_MS_DICT)
        # # 创建单表工作类并初始化
        self.create_table_work_class(self.DEFAULT_MS_DICT)
        self._init_map()
        self._set_label()

        # self._init_ctrl_table()
        self.read_data()
        apply_styles(self)

    def _init_map(self) -> None:
        """
        关系映射
        :return:
        """
        self.label_name = {
            '01.01.01': '生产领料单导入接口（mes➜erp）',
            '01.01.02': '产品入库导入接口（mes➜erp）',
            '01.01.03': '在制品单据导入接口（mes➜erp）',
            '01.02.01': '销售订单导出接口（erp➜mes）',
            '01.02.02': '生产任务单导出接口（erp➜mes）',
            '01.02.03': '物料导入接口（erp➜mes）',
        }

    def _set_label(self) -> None:
        """设置标签"""
        label_name = self.label_name.get(self.ms_number)
        self.lbl_name1.setText(label_name)
        self.lbl_name2.setText(label_name)

    # region  工具栏命令，过滤返回， 行选择变化，表单双击
    def action_select(self, q):
        sel = q.text()
        if  sel == '导出':
            # obj_list = [('生产任务单', self.taskTableView),
            #             ('生产锅单', self.potTableView),
            #             ('领料单', self.pickTableView)]
            # to_excel = TableViewToXls(obj_list)
            # to_excel.to_excel_file()
            pass
        elif sel == '编辑':
            self.on_edit_action()


    def on_edit_action(self):
        """响应表格双击"""
        index = self.tableView.currentIndex()
        if index.isValid():
            row = index.row()
            fid = self.form_model.record(row).value('FId')
            self.read_data_to_form_edit(fid, row)
        else:
            DialogUtils.info('请选中记录', '提示')
            return


    @Slot(QItemSelection, QItemSelection)
    def on_selection_changed(self, selected, deselected) -> None:
        """

        :param selected:
        :param deselected:
        :return:
        """
        indexes = selected.indexes()
        if indexes:
            # sql = self.get_sql('potSql')
            # row = indexes[0].row()
            # task_number = self.taskModel.record(row).value('FBillNo')
            # condition = f" FTaskBillNo='{task_number}'"
            # sql = SqlFunction.add_where_str(sql, condition)
            # self._read_pot_data(sql)
            #
            # sql = self.get_sql('pickSql')
            # sql = SqlFunction.add_where_str(sql, condition)
            # self._read_pick_data(sql)
            pass

    # endregion


    # region 页面数据
    def read_data(self, sql: str = None) -> None:
        """
        读表数据
        :param sql:
        :return:
        """
        if sql is None:
            sql = self.m_form_sql

        field_chn_list = self.f_field_name_list
        self.form_model = FormModel(sql=sql, field_chn_list=field_chn_list)
        self.tableView.setModel(self.form_model)

        self.tableView.set_column_width_by_number(self.f_column_width_list)
        self.tableView.set_visible_column_by_number(self.f_visible_list)

    # endregion


    # region 处理 状态及控制
    def _init_ctrl_table(self) -> None:
        # 1. 显式设置列数（与表头一致，增强稳定性）
        self.tableWidget.setColumnCount(6)
        self.tableWidget.setHorizontalHeaderLabels(["序号", "状态", "名称", "启动时间", "停止时间", "命令选择"])

        data = [
            {"name": "任务A", "start": "08:00", "stop": "12:00"},
            {"name": "任务B", "start": "09:30", "stop": "17:00"},
            {"name": "任务C", "start": "10:15", "stop": "18:45"},
        ]
        self.tableWidget.setRowCount(len(data))

        # 2. 填充数据 + 行高设置（循环内设置，每一行都生效）
        for row, item in enumerate(data):
            # 序号列
            idx_item = QTableWidgetItem(str(row + 1))
            idx_item.setTextAlignment(Qt.AlignCenter)
            self.tableWidget.setItem(row, 0, idx_item)

            # 名称、启动/停止时间列
            for col, text in [(2, item["name"]), (3, item["start"]), (4, item["stop"])]:
                table_item = QTableWidgetItem(text)
                table_item.setTextAlignment(Qt.AlignCenter)
                self.tableWidget.setItem(row, col, table_item)

            # 关键：行高设置移到循环内，每一行都应用 40px 高度
            self.tableWidget.setRowHeight(row, 40)

            # （可选）状态列占位（避免列宽为0）：即使暂时没有图标，也设置一个空的居中标签
            status_label = QLabel()
            status_label.setAlignment(Qt.AlignCenter)
            self.tableWidget.setCellWidget(row, 1, status_label)



            # （可选）命令列占位（避免列宽为0）
            cmd_widget = QWidget()
            cmd_layout = QHBoxLayout(cmd_widget)
            cmd_layout.setContentsMargins(5, 5, 5, 5)

            # 启动按钮
            self.start_btn = TextButton(text="启动", size=40, color="green")  # 绿色
            self.stop_btn = TextButton(text="停止", size=40, color="red")  # 红色

            # 绑定命令
            self.start_btn.clicked.connect(partial(self.on_command, row, "start"))
            self.stop_btn.clicked.connect(partial(self.on_command, row, "stop"))

            cmd_layout.addWidget(self.start_btn)
            cmd_layout.addWidget(self.stop_btn)
            self.tableWidget.setCellWidget(row, 5, cmd_widget)

            # 设置行高
            self.tableWidget.setRowHeight(row, 60)

            # 加一个空的拉伸控件，避免列宽塌陷
            cmd_layout.addStretch()
            self.tableWidget.setCellWidget(row, 5, cmd_widget)

        # 3. 列宽设置（核心优化：确保渲染生效）
        # 先设置表头拉伸模式，再适配内容
        header = self.tableWidget.horizontalHeader()
        # 前5列：自适应内容 + 不可手动调整（避免用户误操作）
        for col in range(5):
            header.setSectionResizeMode(col, QHeaderView.ResizeToContents)

        header.setSectionResizeMode(5, QHeaderView.Stretch)

    # endregion


    def on_command(self, row, action):
        task_name = self.tableWidget.item(row, 2).text()
        print(f"【{task_name}】执行命令: {action} (第 {row + 1} 行)")

        # 核心功能：关闭已打开的PowerPoint
        self.close_running_powerpoint()

    def close_running_powerpoint(self):
        """关闭所有已打开的PowerPoint实例"""
        pythoncom.CoInitialize()  # 初始化COM组件（避免线程问题）
        try:
            # 尝试获取已运行的PowerPoint实例
            ppt_app = win32com.client.GetActiveObject("PowerPoint.Application")
            print("检测到已打开的PowerPoint，正在关闭...")

            # 关闭所有打开的演示文稿（可选：是否提示保存）
            for presentation in ppt_app.Presentations:
                # 0 = 不保存更改；1 = 保存；2 = 取消关闭
                presentation.Close()

            # 退出PowerPoint应用
            ppt_app.Quit()
            print("PowerPoint已成功关闭")

        except Exception as e:
            # 捕获异常（如PowerPoint未打开、权限不足等）
            if "Operation unavailable" in str(e) or "无效的类字符串" in str(e):
                print("未检测到已打开的PowerPoint")
            else:
                print(f"关闭PowerPoint失败：{str(e)}")
        finally:
            pythoncom.CoUninitialize()  # 释放COM组件
    # endregion


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    dic = "{'msFNumber':'05.01','msClass':'11', 'msSaveType':1, 'FPID':-1,'inspecType':0}"
    window = ErpInterface()
    window.show()
    sys.exit(app.exec_())
